<script setup lang="ts">
import { onMounted, ref, shallowRef } from 'vue'
import { useI18n } from 'vue-i18n'
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
import echarts, { ECOption } from '@/plugins/echarts'
import { getCountryStat, getProvinceStat } from '@/api/cms/flowstatistic'

const { t, n } = useI18n()
dayjs.extend(duration)

const dateRange = ref<string>('last30day')
const getBeginByDateRange = (range: string): string | undefined => {
  switch (range) {
    case 'today':
      return dayjs().format('YYYY-MM-DD')
    case 'yesterday':
      return dayjs().subtract(1, 'day').format('YYYY-MM-DD')
    case 'last7day':
      return dayjs().subtract(6, 'day').format('YYYY-MM-DD')
    case 'last30day':
      return dayjs().subtract(29, 'day').format('YYYY-MM-DD')
    case 'lastYear':
      return dayjs().subtract(1, 'year').format('YYYY-MM-DD')
    default:
      return undefined
  }
}

const getEndByDateRange = (range: string): string => {
  if (range === 'yesterday') {
    return dayjs().subtract(1, 'day').format('YYYY-MM-DD')
  }
  return dayjs().format('YYYY-MM-DD')
}

const countryChartRef = shallowRef<HTMLElement>()
const initCountryChart = async (range: string) => {
  const list = await getCountryStat({
    begin: getBeginByDateRange(range),
    end: getEndByDateRange(range)
  })
  const total = list.reduce((acc, curr) => acc + curr.pvCount, 0)
  const option: ECOption = {
    title: {
      text: t('cms.statistic.country'),
      textStyle: { color: '#909399', fontWeight: 'normal', fontSize: 16 }
    },
    tooltip: {
      trigger: 'item',
      valueFormatter: (value: any) => Number(Number(value * 100) / total).toFixed(2) + '%'
    },
    legend: { type: 'scroll', orient: 'vertical', right: '10%', top: 16, bottom: 16 },
    series: [
      {
        name: t('cms.statistic.country'),
        type: 'pie',
        radius: '72%',
        center: ['40%', '56%'],
        data: list.map((item) => ({ value: item.pvCount, name: item.statName }))
      }
    ]
  }
  const chartDom = countryChartRef.value
  if (chartDom == null) {
    return
  }
  let chart = echarts.getInstanceByDom(chartDom)
  if (chart == null) {
    chart = echarts.init(chartDom)
  }
  chart.setOption(option)
  window.addEventListener('resize', function () {
    chart && chart.resize()
  })
}

const provinceChartRef = shallowRef<HTMLElement>()
const initProvinceChart = async (range: string) => {
  const list = await getProvinceStat({
    begin: getBeginByDateRange(range),
    end: getEndByDateRange(range)
  })
  const total = list.reduce((acc, curr) => acc + curr.pvCount, 0)
  const option: ECOption = {
    title: {
      text: t('cms.statistic.province'),
      textStyle: { color: '#909399', fontWeight: 'normal', fontSize: 16 }
    },
    tooltip: {
      trigger: 'item',
      valueFormatter: (value: any) => Number(Number(value * 100) / total).toFixed(2) + '%'
    },
    legend: { type: 'scroll', orient: 'vertical', right: '10%', top: 16, bottom: 16 },
    series: [
      {
        name: t('cms.statistic.province'),
        type: 'pie',
        radius: '72%',
        center: ['40%', '56%'],
        data: list.map((item) => ({ value: item.pvCount, name: item.statName }))
      }
    ]
  }
  const chartDom = provinceChartRef.value
  if (chartDom == null) {
    return
  }
  let chart = echarts.getInstanceByDom(chartDom)
  if (chart == null) {
    chart = echarts.init(chartDom)
  }
  chart.setOption(option)
  window.addEventListener('resize', function () {
    chart && chart.resize()
  })
}

const initChart = async (range: string) => {
  initCountryChart(range)
  initProvinceChart(range)
}

onMounted(async () => {
  initChart(dateRange.value)
})
</script>

<template>
  <div>
    <div class="p-3 mt-3 app-block">
      <div>
        <el-radio-group v-model="dateRange" @change="(value: any) => initChart(value)">
          <el-radio-button
            v-for="item in ['today', 'yesterday', 'last7day', 'last30day', 'lastYear', 'all']"
            :key="item"
            :label="item"
          >
            {{ $t(`cms.access.${item}`) }}
          </el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <el-row :gutter="12">
      <el-col :span="12">
        <div class="p-3 mt-3 app-block">
          <div ref="countryChartRef" class="h-80"></div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="p-3 mt-3 app-block">
          <div ref="provinceChartRef" class="h-80"></div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
